package com.yb.mini.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @author yangbiao
 * @date: 2024/03/13
 */
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    private final String START_TIME = "START_TIME";

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //记录访问开始时间
        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            final Long startTime = exchange.getAttribute(START_TIME);
            if (Objects.nonNull(startTime)) {
                final long currentTime = System.currentTimeMillis();
                final ServerHttpRequest request = exchange.getRequest();
                final String host = request.getURI().getHost();
                final int port = request.getURI().getPort();
                final String path = request.getURI().getPath();
                log.warn("请求{}:{}{}#请求耗时{}毫秒", host, port, path, currentTime - startTime);
            }
        }));
    }

}
